# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt

import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSInspectionPlan(Document):
	# 提交前检验: 同一个设备只能有一个提交状态,并且是否停止等于0,并且频率相同的(不同频率,比如日点检和周点检可以共存)
	def before_submit(self):
		if frappe.db.exists({"doctype": self.doctype, "equipment_card": self.equipment_card, "is_stoped": 0, "docstatus": 1, "periodicity": self.periodicity}):
			frappe.throw(_("EMS Inspection Plan {0} Is Running. The BillNo is:{1}").format(self.periodicity, frappe.db.exists({"doctype": self.doctype, "equipment_card": self.equipment_card, "is_stoped": 0, "docstatus": 1, "periodicity": self.periodicity})))

	def on_cancel(self):
		frappe.db.set_value(self.doctype, self.name, {"is_stoped": 1})
		self.reload()


# 点检方案生成点检单
@frappe.whitelist()
def make_inspection_doc(source_name, target_doc=None, args=None):
	doc = get_mapped_doc(
		"EMS Inspection Plan",
		source_name,
		{
			"EMS Inspection Plan": {
				"doctype": "EMS Inspection Doc",
				"field_map": {"name": "inspection_plan", "start_date": "expected_inspection_date"},
				"validation": {"docstatus": ["=", 1], "is_stoped": ["=", 0]},
			},
			"EMS Inspection Plan Item": {
				"doctype": "EMS Inspection Doc Item",
				"field_map": {},
			},
		},
		target_doc,
		ignore_permissions=True,
	)
	# 修改预计点检日期
	doc.expected_inspection_date = frappe.utils.getdate()

	return doc


# 点检方案生成点检单
@frappe.whitelist()
def make_inspection_doc_schedule():
	plans = frappe.db.get_all('EMS Inspection Plan', filters={"is_stoped": 0, "docstatus": 1})
	for i in plans:
		# 先判断当前点检方案是否已经有生成过点检单: 如果没生成过则不自动生成
		if frappe.db.exists({"doctype": "EMS Inspection Doc", "inspection_plan": i.name}):
			# 找到最后一张(根据预计点检日期排序)点检单的下个点检日期
			last_inspection_next_date = frappe.db.get_all(	"EMS Inspection Doc", 
											filters={"inspection_plan": i.name,"inspection_stoped": 0},
											fields=["inspection_next_date"],
											order_by="expected_inspection_date desc",
											page_length=1,
										)
			# 判断下个点检日期是否小于或等于(按照正常业务逻辑应该就等于今天日期),满足条件则自动生成当天的点检单
			if last_inspection_next_date[0]["inspection_next_date"] <= frappe.utils.getdate():
				source_name=i.name
				target_doc=None
				doc = get_mapped_doc(
					"EMS Inspection Plan",
					source_name,
					{
						"EMS Inspection Plan": {
							"doctype": "EMS Inspection Doc",
							"field_map": {"name": "inspection_plan", "start_date": "expected_inspection_date"},
							"validation": {"docstatus": ["=", 1], "is_stoped": ["=", 0]},
						},
						"EMS Inspection Plan Item": {
							"doctype": "EMS Inspection Doc Item",
							"field_map": {},
						},
					},
					target_doc,
					ignore_permissions=True,
				)
				# 修改预计点检日期
				doc.expected_inspection_date = frappe.utils.getdate()
				print(doc.name)
				doc.save()
